//
//  RecordSetController.m
//  mark
//
//  Created by student5 on 2021/12/17.
//

#import <Foundation/Foundation.h>
#import "RecordSetController.h"
#import "detailView.h"


@interface RecordSetController()
@property UIButton *backButton;
@property(nonatomic,strong)UINavigationBar *navigationBar;
@property(nonatomic,strong)UILabel *timeSettingLabel;
@property(nonatomic,strong)UIDatePicker *datePicker; //时间设置组件
@property(nonatomic,strong)UISlider *slider;//滑动条
@property(nonatomic,strong)UISwitch *isUseTimeSwitch;//switch
@property(nonatomic,strong)UIButton *applyButton;
@property(nonatomic,strong)UIButton *deleteButton;
//@property(nonatomic,strong)NSString *index_str;//储存当前的记录的路径的那个数字
@end

@implementation RecordSetController

-(void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];//这个是必须要的，否则动画效果会不太一样
    [self setNavigationbar];//设置导航栏
    [self backbtn];         //返回按钮和导航栏是独立的，并没有添加到导航栏里面
    [self set_wordSettingLabel]; //文字“”
    [self set_slider];           //滑动条
    [self set_autoSettingLabel]; //文字“”
    [self set_switch];
    [self setupDatePicker];
    [self applybtn];//应用按钮
    [self deletebtn];//删除按钮
}




- (void)backbtn{  //返回主界面
    self.backButton = [[UIButton alloc]initWithFrame:CGRectMake(20, 28, 50, 30)];
    [self.backButton setTitle:@"返回"forState:UIControlStateNormal];
    self.backButton.layer.cornerRadius = 5;
    self.backButton.layer.borderWidth = 1;
    self.backButton.layer.borderColor = [UIColor grayColor].CGColor;
    [self.backButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside];//添加事件
    
    [self.view addSubview:self.backButton];

}



-(void)backButtonPressed:(id)sender{ //返回按钮点击
    NSLog(@"backButtonPressed");
    //跳转到上一个页面，也就是记录查看页面
    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}



-(void)setNavigationbar{//设置导航栏
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    UINavigationBar *navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 20, screenRect.size.width, 80.0f)];

    //self.navigationItem.rightBarButtonItem = self.set_item;
    //创建UINavigationItem
    UINavigationItem *navigationBarTitle = [[UINavigationItem alloc] initWithTitle:@"设置"];
    NSDictionary *attrs = @{NSFontAttributeName : [UIFont systemFontOfSize:20]};
    [navigationBar setTitleTextAttributes:attrs];
    [navigationBar pushNavigationItem:navigationBarTitle animated:YES];
    [self.view addSubview: navigationBar];
    
    [navigationBar setItems:[NSArray arrayWithObject: navigationBarTitle]];//这句不知道用来作什么，去掉了也一样
}




//文字“字体大小”
-(void)set_wordSettingLabel{
    self.timeSettingLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 200, 50)];
    self.timeSettingLabel.text = @"字体大小：";
    self.timeSettingLabel.font = [UIFont fontWithName:@"Arial" size:20.0f];
    self.timeSettingLabel.textColor = [UIColor blackColor];
    [self.view addSubview:self.timeSettingLabel];
}



//设置滑动条
-(void)set_slider{
    // 初始化
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake((self.view.bounds.size.width-200)/2, 150, 200, 20)];
    self.slider.value = self.slider_value;
    [self.view addSubview:self.slider];
    [self.slider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];// 针对值变化添加响应方法
    
}



-(void)sliderValueChanged:(id)sender{
    NSLog(@"%@", [[NSNumber alloc] initWithFloat:self.slider.value]);
}




//文字“设置提醒时间”
-(void)set_autoSettingLabel{
    self.timeSettingLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 200, 200, 50)];
    self.timeSettingLabel.text = @"设置提醒时间：";
    self.timeSettingLabel.font = [UIFont fontWithName:@"Arial" size:20.0f];
    self.timeSettingLabel.textColor = [UIColor blackColor];
    [self.view addSubview:self.timeSettingLabel];
}




//设置switch
-(void)set_switch{
    self.isUseTimeSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(170, 210, 100, 30)];
    //默认开启
    [self.isUseTimeSwitch setOn:true animated:true];
    //设置监听事件
    [self.isUseTimeSwitch addTarget:self action:@selector(SwitchChange:) forControlEvents:(UIControlEventValueChanged)];
    [self.view addSubview:self.isUseTimeSwitch];
}




//事件响应函数
-(void)SwitchChange:(UISwitch *)sender{
    if([sender isOn]){
        NSLog(@"switch is on!");
        self.datePicker.enabled = YES;
        //在此处添加功能设定
    }
    else{
        NSLog(@"switch is off!");
        self.datePicker.enabled = NO;
        //在此处添加功能设定
    }
}




- (void)setupDatePicker {
    //因为datapicker
    UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(50, 270, 150, 40)];
    /*NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];*/
    
    //设置地区: zh-中国
    datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
    
    //设置日期模式(Displays month, day, and year depending on the locale setting)
    datePicker.datePickerMode = UIDatePickerModeDateAndTime;
    // 设置当前显示时间，从文件中提取
    NSString *time_str = [NSString stringWithContentsOfFile:self.data_path[1] encoding:NSUTF8StringEncoding error:nil];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm a"];  //格式设置
    [datePicker setDate:[dateFormatter dateFromString:time_str] animated:YES];
    
    self.datePicker = datePicker;
    
    [self.view addSubview:self.datePicker];
}




- (void)applybtn{  //应用
    self.applyButton = [[UIButton alloc]initWithFrame:CGRectMake(100, 400, self.view.bounds.size.width-200, 40)];
    [self.applyButton setTitle:@"应用"forState:UIControlStateNormal];

    [self.applyButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.applyButton addTarget:self action:@selector(applyButtonPressed:) forControlEvents:UIControlEventTouchUpInside];//添加事件
    self.applyButton.layer.borderColor = [UIColor grayColor].CGColor;
    self.applyButton.layer.borderWidth = 1.0f;
    self.applyButton.layer.cornerRadius = 5.0f;
    [self.view addSubview:self.applyButton];
}




-(void)applyButtonPressed:(id)sender{ //应用按钮点击
    NSLog(@"applyButtonPressed");
    //
    NSError *error;
    //存时间
    NSString *dateString = [self getdate:self.datePicker];
    [dateString writeToFile:self.data_path[1] atomically:YES encoding:NSUTF8StringEncoding error:&error];//存储date
    
    //存字体大小，未实现
    /*1. 在创建时，创建一个文件，存储初始的字体大小。
     2. 在ViewController.m文件中添加字体大小数组的变量。
     3.在ViewController.m 的-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath中为传输数据数据添加新的对象
     4.修改ViewController.m函数addData
     5.修改ViewController.m函数deleteData
     6.detail页面要读取存储下来的字体大小。
     7.RecordSetController中修改后要重写文件，直接用writetofile
     
     ps：可以转为int转为string存入文件，读取后再从string转回int
     */
    //等网页显示实现以后再实现
    
    [self cancel_notification:self.data_path[2]]; //传入参数是url的存储地址,删除记录
    [self send_notification:self.datePicker.date index:self.data_path[2]]; //重新设置一个新的提醒
    [self.father_view set_content_font_size:self.slider.value];
    //跳转到起始页面
    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}




//获取设置好的时间
- (NSString*)getdate:(UIDatePicker *)datePicker {
    //从datepicker中获取时间NSDate类型
    NSLog(@"getdate");
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    //设置时间格式
    formatter.dateFormat = @"yyyy-MM-dd hh:mm a";
    NSString *dateStr = [formatter  stringFromDate:datePicker.date];
    
    return dateStr;
}




- (void)deletebtn{  //删除记录
    self.applyButton = [[UIButton alloc]initWithFrame:CGRectMake(100, 470, self.view.bounds.size.width-200, 40)];
    [self.applyButton setTitle:@"删除记录"forState:UIControlStateNormal];
    self.applyButton.backgroundColor = [UIColor redColor];

    [self.applyButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.applyButton addTarget:self action:@selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];//添加事件
    self.applyButton.layer.borderColor = [UIColor grayColor].CGColor;
    self.applyButton.layer.borderWidth = 1.0f;
    self.applyButton.layer.cornerRadius = 5.0f;
    [self.view addSubview:self.applyButton];
}




-(void)deleteButtonPressed:(id)sender{ //删除按钮点击
    NSLog(@"deleteButtonPressed");
    //跳转到起始页面
    //deleteRecord  //删除记录的函数
    //回到主界面
    [self cancel_notification:self.data_path[2]]; //传入参数是url的存储地址,删除记录
    [self.father_view send_delete_message];
    NSLog(@"recordSetController send successful");
    [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}




//取消对应的推送，传入参数是url的存储路径
-(void)cancel_notification:(NSString *)index_str{
    NSLog(@"Application did receive local notifications");
    
    // 取消某个特定的本地通知
    for (UILocalNotification *noti in [[UIApplication sharedApplication] scheduledLocalNotifications]) { //遍历所有的notification
        NSString *notiID = [noti.userInfo objectForKey:@"key"];
        if ([notiID isEqualToString:index_str]) { //index_str是存储文件对应的那个数字
            [[UIApplication sharedApplication] cancelLocalNotification:noti];
            return;
        }
    }
    
    NSLog(@"can not find the notification!");
}





//设置新的notification，传入参数是url的存储路径
-(void)send_notification:(NSDate *)date index:(NSString *)index_string{
    // 授权通知
    UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:setting];

    //创建通知，在app运行时不会弹出，回到主界面
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    if (nil != notification){
        NSLog(@"send notification!");
        NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
        dateFormatter.dateFormat = @"yyyy-MM-dd hh:mm a";
        //设置通知弹出的时间
        notification.fireDate = date;
        //设置重复重复间隔为每天
        notification.repeatInterval = kCFCalendarUnitDay;
        // 设置时区
        notification.timeZone= [NSTimeZone defaultTimeZone];
        //设置提示消息
        notification.alertBody = [NSString stringWithFormat:@"%@",@"你有未看的记录"];
        //取消推送用的字典便于识别 forkey:@"key" nsstring 存储地址对应的那个数字
        //NSString *index_string = [NSString stringWithFormat:@"%d",index];
        NSDictionary * Dic = [NSDictionary dictionaryWithObject:index_string forKey:@"key"];
        notification.userInfo = Dic;
        // 启动通知
        [[UIApplication sharedApplication]scheduleLocalNotification:notification];
    }
}
@end
